package com.example.loginsystem.api;

import com.example.loginsystem.model.Result;
import com.example.loginsystem.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;

/**
 * @author Cheung0
 * Created on 2021/12/4
 */
@RestController
public class uploadAPI {

    private File imageDirectory = new File("Resources" + File.separator + "messageImg").getAbsoluteFile();

    @PostConstruct
    private void initDirectory() {
        if (!imageDirectory.exists()) {
            imageDirectory.mkdirs();
        }
    }

    @RequestMapping(value = "/api/upload", method = RequestMethod.PUT)
    public Result<String> upload(@RequestParam("image") MultipartFile image) {
        Result<String> result = new Result<>();
        if (image.isEmpty()) {
            result.setResultFailed("请上传图片！");
            return result;
        }
        if (image.getSize() > 4194304) {
            result.setResultFailed("上传图片大小必须在4MB以内！");
            return result;
        }
        String fileFormat = image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf("."));
        if (!fileFormat.equals(".jpg") && !fileFormat.equals(".png") && !fileFormat.equals(".bmp") && !fileFormat.equals(".gif")) {
            result.setResultFailed("上传图片必须是jpg、png、bmp或者gif格式！");
            return result;
        }
        String fileName = UUIDUtils.generateUUID() + fileFormat;
        try {
            image.transferTo(new File(imageDirectory.getPath() + File.separator + fileName));
        } catch (Exception e) {
            e.printStackTrace();
            result.setResultFailed("图片转存失败！请联系管理员！");
            return result;
        }
        result.setResultSuccess("上传图片成功！", "/messageImg/" + fileName);
        return result;
    }

}
